//
// Created by bd on 2019/11/12.
//

#include <iostream>
#include <event2/event.h>
#include <csignal>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <thread>

using namespace std;

static void read_file_cb(evutil_socket_t fb, short which, void *arg)
{
    char buf[1024] = {0};
    auto len = read(fb, buf, sizeof(buf)-1);
    if (len > 0) {
        cout << buf << flush;
    } else {
        cout << "." << flush;
        this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

int main()
{
    // 忽略管道信号，发送数据给已关闭的socket
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return 1;

    auto conf = event_config_new();
    // 设置支持文件描述符
    event_config_require_features(conf, EV_FEATURE_FDS);
    auto base = event_base_new_with_config(conf);
    event_config_free(conf);
    if (!base) {
        cerr << "event base new failed, exit." << endl;
        return 1;
    }

    // 打开文件，只读，非阻塞
    auto fb = open("./test.log", O_RDONLY | O_NONBLOCK, 0);
    if (fb <= 0) {
        cerr << "open ./test.log failed" << endl;
        event_base_free(base);
        return 1;
    }

    // 移动到文件结尾
    lseek(fb, 0, SEEK_END);

    auto *ev = event_new(base, fb, EV_READ|EV_PERSIST, read_file_cb, nullptr);
    event_add(ev, nullptr);

    event_base_dispatch(base);
    event_base_free(base);
    return 0;
}